package com.maotai.llzhou.thread;

import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.bean.ProductInfo;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.FaceUtil;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;

/**
 * 登录并且抢购
 */
public class MaotaiQueryOrderThread extends Thread {
//https://www.emaotai.cn/SendPayment.aspx?orderId=
	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;

	public MaotaiQueryOrderThread(MaotaiService maotaiService,
			Map<String, Object> zhanghao, String ipAndPort) {
		super();
		this.maotaiService = maotaiService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	@Override
	public void run() {
		try {
			MaotaiWebCookie mwc = new MaotaiWebCookie();
			HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
			if (zhanghao.get("auth") == null
					|| "".equals(zhanghao.get("auth"))) {
				// 先执行登录操作
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				zhanghao.put("orderstatus", "0");
				maotaiService.updateZhanghaoOrderStatus(zhanghao);
				return;
			}
			
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
			String name = zhanghao.get("name")+"";
            String certNumber = zhanghao.get("certNumber")+"";			
			mwc.setAuth(zhanghao.get("auth") + "");
//			String timestamp = System.currentTimeMillis()+"";
//			String sign = JSUtil.excuFunctionA(mwc.getAuth()+timestamp);
//			mwc.setSign(sign);
//			mwc.setTimestamp(timestamp);
			mwc = hcu.sendHttpGetProxy(MaotaiString.ORDER_QUERY_URL_NEW,
					mwc, config, MaotaiString.ORDER_REFERER);
			if(mwc.getContent()!=null){
				String return_str = mwc.getContent();
				System.out.println("------账号结束:"+zhanghao.get("code")+"------"+return_str);
				if(mwc.getContent().contains("login")){
					zhanghao.put("loginstatus", "0");
					maotaiService.updateZhanghaoLoginStatus(zhanghao);
					zhanghao.put("orderstatus", "0");
					maotaiService.updateZhanghaoOrderStatus(zhanghao);
					return;
				}
				//{"data":{"endRow":0,"firstPage":0,"hasNextPage":false,"hasPreviousPage":false,"isFirstPage":false,"isLastPage":false,"lastPage":0,"list":[{"delivery":{"address":"江苏，无锡市，新区吼山南路591号龙记首饰","addressId":null,"areaCode":"0","areaName":null,"cityCode":"320200000000","cityName":null,"deliveryBearName":null,"deliveryCompany":null,"deliveryCompanyLogo":null,"deliveryCompanyMobile":null,"deliveryCompanyName":null,"deliveryId":null,"deliveryIdName":null,"deliveryMobile":"13438822775","deliveryName":"朱根","deliveryPhone":"","deliveryType":1,"detailed":"江苏，无锡市，新区吼山南路591号龙记首饰","logisticsBear":null,"logisticsBearCode":null,"logisticsCompany":null,"logisticsCompanyDesc":"顺丰快递（贵）","logisticsCost":null,"logisticsId":null,"orderId":2265740,"postcode":null,"provinceCode":"320000000000","provinceName":null,"remark":null,"returnApplyId":null,"sendImgUrl":null,"streetCode":null,"streetName":null,"waybillNo":"620792631228"},"invoice":{"bankAccount":"","createPerson":"2018-06-26 06:24:51.017","createTime":"2018-06-15 11:09:37","id":198624,"invoiceContent":"明细","invoiceContentType":1,"invoiceNo":null,"invoiceTaxType":null,"invoiceTaxTypeName":null,"invoiceTitle":"朱根","invoiceTitleType":1,"invoiceTitleTypeName":"个人","invoiceType":2,"invoiceTypeName":"电子发票","invoiceUrl":null,"isGenerated":0,"openBank":"","orderCreateTime":null,"orderId":2265740,"orderNo":"2018061501081","orgName":null,"payAmount":7495.00,"receiverEmail":null,"receiverPhone":null,"registerAddress":"","registerPhone":null,"taxCode":"","unitName":null,"updatePerson":"migration program","updateTime":"2018-06-15 11:09:37"},"orderGifts":null,"orderItems":[{"actualSubtotalAmount":7495.00,"alReturnNum":0,"brandId":7,"canReturnNum":null,"catalogId":1,"createPerson":"migration program","createTime":"2018-06-15 10:00:07","freightInsuranceFee":7495.00,"hasEvaluation":false,"hasReturn":null,"id":730376,"imgUrl":null,"isPartialShipment":null,"itemCode":"1","itemDiscountedPrice":1499.00,"itemGifts":null,"itemId":1,"itemItem":false,"itemName":"贵州茅台酒 新飞天茅台酒53度500ml茅台官方商城正品直供","itemNum":5,"itemPrice":1499.00,"itemTeamData":null,"itemTeamDtos":[],"itemType":1,"memberId":3288273,"orderId":2265740,"orderPayAmount":null,"platformDiscountPrice":null,"platformTotalDiscountPrice":null,"redAlertPrice":1065.00,"scanCodeInfo":[],"sellOut":null,"sellerId":520100258,"shopDiscountPrice":null,"shopId":"1173773178264259584","shopItemCode":"23","shopTotalDiscountPrice":null,"skuDesc":null,"skuId":9,"status":null,"statusName":null,"subtotalAmount":7495.00,"updatePerson":null,"updateTime":"2018-06-15 10:00:07","voucherSubtotalAmount":null}],"orderMain":{"abortTime":null,"activityDiscountAmount":null,"allRefundSucc":false,"allRefunding":false,"auditStatus":null,"canPay":false,"canRefund":true,"canRepeatBuy":false,"canReturn":true,"cancelDesc":null,"cancelTime":null,"cancelType":null,"channelId":1,"channelName":null,"cityDeliverySendOut":null,"collectTime":null,"commissionAmount":null,"couponAmount":null,"createPerson":null,"createTime":null,"deliverBeginTime":null,"deliverEndTime":null,"errorReason":null,"fetchCode":null,"fetchStatus":null,"financeExamineTime":null,"financeRejectReason":null,"finishTime":null,"freightAmount":0.00,"frozenStatus":null,"gatheringNum":null,"giftTotalAmount":null,"hasRefund":false,"hasReturn":null,"id":2265740,"inRejection":false,"interceptReason":null,"inventorySendOut":false,"isError":null,"isFetch":null,"isPartialShipment":0,"isQrBuy":0,"isSelfSupport":null,"isSettlement":null,"itemAmount":0,"memberId":null,"memberNickName":null,"memberUsername":null,"needFinanceAudit":null,"needVisitAudit":null,"obligationNum":null,"offlinePayMethod":null,"operateType":null,"operateTypeName":null,"orderNo":"2018061501081","orderPayError":false,"orderPayIng":false,"orderTime":"2018-06-15 10:00:07","originalStatus":5,"parentId":null,"payAmount":7495.00,"payChannelName":null,"payEndTime":null,"payErrorReason":null,"payMethod":null,"payMethodName":null,"payOnlineOff":"在线支付","payTime":null,"platformDiscountAmount":null,"pointDiscountAmount":null,"preH5Url":null,"preTreated":null,"priceSysOpen":null,"redAlertPriceOutOf":null,"refundNos":[],"remark":null,"sellerId":null,"sellerRemark":"无备注","settlementMsg":null,"settlementStatus":null,"settletMentTime":null,"shippingTime":null,"shopDiscountAmount":null,"shopId":"1173773178264259584","shopName":"茅台商城","sourceOrderNo":null,"sourceShopNo":null,"status":5,"statusName":"已签收","totalAlReturnNum":0,"totalDiscountAmount":null,"totalItemNum":5,"totalRealRefundAmount":null,"totalRealReturnAmount":null,"transactionType":null,"updatePerson":null,"updateTime":null,"visitExamineTime":null,"visitRejectReason":null}}],"navigatePages":0,"navigatepageNums":null,"nextPage":0,"orderBy":null,"pageNum":1,"pageSize":5,"pages":1,"prePage":0,"size":0,"startRow":0,"total":1},"resultCode":0,"resultMsg":"success"}
				JSONObject data = JSONObject.parseObject(return_str).getJSONObject("data");
				JSONArray list = data.getJSONArray("list");
				if(list!=null && list.size()>0){
					for(int j=0;j<list.size();j++){
						JSONObject temp = (JSONObject)list.get(j);
						JSONObject delivery = temp.getJSONObject("delivery");
						String address = delivery.getString("address");//"address": "江苏，无锡市，新区吼山南路591号龙记首饰",
						String deliveryMobile = delivery.getString("deliveryMobile");//"deliveryMobile": "13438822775",
						String deliveryName = delivery.getString("deliveryName");//"deliveryName": "朱根",
						String logisticsCompanyDesc = delivery.getString("logisticsCompanyDesc");//"logisticsCompanyDesc": "顺丰快递（贵）",
						String orderId = delivery.getString("orderId");//"orderId": 2265740,
						String waybillNo = delivery.getString("waybillNo");//"waybillNo": "620792631228"
						
//						JSONArray orderItems = temp.getJSONArray("orderItems");
//						if(orderItems!=null && orderItems.size()>0){
//							for(int j=0;j<orderItems.size();j++){
//								JSONObject tempitem = (JSONObject)orderItems.get(i);
//								String actualSubtotalAmount = tempitem.getString("actualSubtotalAmount");
//								String createTime = tempitem.getString("createTime");
//								String id = tempitem.getString("id");
//								String itemName = tempitem.getString("itemName");
//								String itemNum = tempitem.getString("itemNum");
//								String itemPrice = tempitem.getString("itemPrice");
//								
//							}
//						}
						JSONObject orderMain = temp.getJSONObject("orderMain");
						String orderNo = orderMain.getString("orderNo");//"orderNo": "2018061501081",
						String orderTime = orderMain.getString("orderTime");//"orderTime": "2018-06-15 10:00:07",
						String payAmount = orderMain.getString("payAmount");//"payAmount": 7495.00,
						String payOnlineOff = orderMain.getString("payOnlineOff");//"payOnlineOff": "在线支付",
						String shopId = orderMain.getString("shopId");//"shopId": "1173773178264259584",
						String shopName = orderMain.getString("shopName");//"shopName": "茅台商城",
						String status = orderMain.getString("status");//"status": 5,
						String statusName = orderMain.getString("statusName");//"statusName": "已签收",
						zhanghao.put("address", address);
						zhanghao.put("deliveryMobile", deliveryMobile);
						zhanghao.put("deliveryName", deliveryName);
						zhanghao.put("kuaiditype", logisticsCompanyDesc);
						zhanghao.put("orderId", orderId);
						zhanghao.put("kuaidicode", waybillNo);
						zhanghao.put("orderNo", orderNo);
						zhanghao.put("orderTime", orderTime);
						zhanghao.put("payAmount", payAmount);
						zhanghao.put("payOnlineOff", payOnlineOff);
						zhanghao.put("shopId", shopId);
						zhanghao.put("shopName", shopName);
						zhanghao.put("status", status);
						zhanghao.put("statusName", statusName);
						//maotaiService.insertZhanghaoOrderItem(zhanghao);
						//判断订单状态
						//9 已取消
						//1 待付款
						//点击立即付款
						if("1".equals(status)){
							zhanghao.put("buystatus", "1");
							//maotaiService.updateZhanghaoBuyStatus(zhanghao);
							//maotaiService.insertZhanghaoOrderItem(zhanghao);
							
							//增加扫人脸
							 //获得metainfo
							int mtBizId = 3;
							String zimId = "";
				            String bizId = "";
				            Map<String, Object> tokenMap = maotaiService.getTokenRandom();
				            String apdidToken = tokenMap.get("token")+"";
				            
				            String clearurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/clear?mtBizId=6&appCode=1&_t="+System.currentTimeMillis();
							mwc = hcu.sendHttpGetProxy(clearurl,mwc,config,"");
				            
				            
					        JSONObject uploadJ = new JSONObject();
					        uploadJ.put("apdidToken",apdidToken+""+System.currentTimeMillis()) ;
					        uploadJ.put("appName","com.emaotai.ysapp") ;
					        uploadJ.put("appVersion",ProductInfo.PRODUCT_VERSION) ;
					        uploadJ.put("bioMetaInfo","3.3.0:98304,0") ;
					        uploadJ.put("deviceModel","M8"+System.currentTimeMillis()) ;
					        uploadJ.put("deviceType","android") ;
					        uploadJ.put("osVersion","6.0.1") ;
					        uploadJ.put("zimVer","1.0.0") ;
					        //System.out.println(uploadJ.toJSONString());
					        //将metainfo传到茅台服务端，得到 "zimId" : "e1570236d1cee15043f1823e202d628b",
//					        String initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/init?mtBizId="+mtBizId+"&metainfo="+ URLEncoder.encode(uploadJ.toJSONString());
//					        // "bizId" : "EMAOTAI_20180814093735856536",
//					        for(int j=0;j<20;j++) {
//					        	mwc = hcu.sendHttpGetAppProxy(initUrl, mwc, config, null);
//					            // "bizId" : "EMAOTAI_20180814093735856536",
//					        	System.out.println(zhanghao.get("code")+"----初始化摄像头----" + mwc.getContent());
//					            if (mwc.getContent().contains("重试")||mwc.getContent().contains("Invalid")||mwc.getContent().contains("抱歉")||mwc.getContent().contains("query")) {
//					            	Thread.sleep(1000);
//					                continue;
//					            } else {
//					                break;
//					            }
//					        }
					      //采用最新的post
					        String initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/init";
					        //String postData = "auditType=1&certNumber=320922198607240034&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName=%E5%91%A8%E4%BA%AE%E4%BA%AE";
					        String postData = "auditType=1&certNumber="+certNumber+"&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode(name,"utf-8");
					        for(int i=0;i<20;i++) {
					        	 mwc = hcu.sendHttpPostAppProxy(initUrl, mwc, postData, config);
					            System.out.println(zhanghao.get("code")+"----初始化订单查询摄像头----" + mwc.getContent());
					            if (mwc.getContent().contains("重试")||mwc.getContent().contains("抱歉")||mwc.getContent().contains("query")) {
					            	clearurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/clear?mtBizId="+mtBizId+"&appCode=1&_t="+System.currentTimeMillis();
									mwc = hcu.sendHttpGetProxy(clearurl,mwc,config,"");
					            	Thread.sleep(10000);
					                continue;
					            } else {
					                break;
					            }
					        }
					        if(mwc!=null && mwc.getContent()!=null){
					            JSONObject initJson = JSON.parseObject(mwc.getContent()).getJSONObject("data");
					            zimId = initJson.getString("zimId");
					            bizId = initJson.getString("bizId");
					            
					        }
					        //然后发起认证，认证完了回传到茅台服务器
				            //最后提交预约信息
					        if("".equals(zimId)||"".equals(bizId)) {
//					        	addrMap.put("usestatus", "0");
//								maotaiService.updateAddressLibraryStatus(addrMap);
					        	return;
					        }
					        
					        boolean isFace = FaceUtil.faceToken(apdidToken, zimId,config,zhanghao);
					        if(!isFace){
					        	return;
					        }
					        initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/query?zimId="+zimId+"&bizId="+bizId+"&mtBizId="+mtBizId+"&auditType=1";
					        mwc = hcu.sendHttpGetAppProxy(initUrl,mwc,config,null);
					        System.out.println(zhanghao.get("code")+"----识别结束提交服务器----"+mwc.getContent());
					    	
					        //20180825茅台改为网页去验证，不在手机端提交查询
					        String refererurl = "https://www.emaotai.cn/smartsales-b2c-web-pc/deal";
					        //https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId=2&appCode=1&_t=1535153490878
					        initUrl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId="+mtBizId+"&appCode=1";
					        mwc = hcu.sendHttpGetProxy(initUrl,mwc,config,refererurl);

					        System.out.println(zhanghao.get("code")+"--"+"----查询识别结果----"+mwc.getContent());
					        if(mwc!=null && !mwc.getContent().contains("success")){
					            System.out.println(zhanghao.get("code")+"--"+"----识别结果未成功");
					            for(int h=0;h<5;h++){
					            	mwc = hcu.sendHttpGetProxy(initUrl,mwc,config,refererurl);
					                System.out.println(zhanghao.get("code")+"--"+"----"+mwc.getContent());
					                if(mwc!=null && mwc.getContent().contains("success")){
					                    break;
					                }
					            }
					        }
					        if(mwc!=null && !mwc.getContent().contains("success")){
					        	return;
					        }
							
							
							//https://www.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/order/myorder/quickpay?orderId=1180477610631884809&appCode=1&_t=1531122120292
							//{"data":{"isPay":false,"orderNoArray":null,"sign":null,"orderList":null,"payEndTime":"2018-07-09 18:42:00","isMergePay":0,"errorMsg":null,"payNo":"200115637325018565","payAmount":49.00,"isError":false,"isSelfSupport":1,"html":"","payInfo":null},"resultCode":0,"resultMsg":"success"}
							String quickurl = MaotaiString.QUICK_PAY_URL.replace("xxx", orderId);
							mwc = hcu.sendHttpGetProxy(quickurl, mwc, config, MaotaiString.QUICK_PAY_REFERER_URL);
							System.out.println(zhanghao.get("code")+"---"+mwc.getContent());
							if(mwc.getContent()!=null && mwc.getContent().contains("payNo")){
								//获取payNo
								JSONObject quickPayObj = JSONObject.parseObject(mwc.getContent()).getJSONObject("data");
								String payNo = quickPayObj.getString("payNo");
								//提交支付宝付款，得到返回结果
								//https://www.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/order/paytype/update?appCode=1&_t=1531122124349
								//payNo=200115637325018565&payChannel=ALIPAY&bankCode=undefined&payMethod=200
								//{"data":{"isPay":false,"orderNoArray":null,"sign":"C23739A67A478A89BFF4AB8B6F87A702","orderList":null,"payEndTime":null,"isMergePay":0,"url":null,"errorMsg":null,"payNo":"200031662051418446","payAmount":49.0,"isError":false,"isSelfSupport":1,"html":"<html><head><title>自动跳转页面</title></head><body><script language=\"javascript\">window.location.href='https://pay.cmaotai.com/epay/pay/orderPay2?sysId=400001&interfaceName=alipay_pc&interfaceVersion=1.0.0.2&qid=53530207&tranData=eyJhY3Rpdml0eSI6IiIsIm5vdGlmeVVybCI6Imh0dHBzOi8vbXRwYXkuY21hb3RhaS5jb20venlub3RpZnkiLCJvcmRlckRlc2MiOiIiLCJvcmRlcklkIjoiMjAxODA3MDkxNTM1MjcwMDQ5NzciLCJzdWJqZWN0Ijoi6LS15bee6IyF5Y+w6ZuG5Zui55S15a2Q5ZWGLi4uIiwidG90YWxGZWUiOiI0OTAwIn0=&signData=07A34125757F99B5B0B17A3C9D8330ED&clientType=pc&busiid=10001';</script></body></html>\r\n","payInfo":"{\"channelNo\":\"ZY\",\"couponAmount\":0.00,\"goodsDetails\":[{\"goodsId\":1174321461468499968,\"goodsName\":\"茅台喜庆红葡萄酒（蓝）11%vol 750ml\",\"goodsPrice\":49.00,\"goodsType\":1,\"num\":1,\"unit\":0}],\"invoiceFlag\":1,\"merBranchId\":\"201804261530030001\",\"merchantId\":\"520100258\",\"orderId\":\"20180709153527004977\",\"payAmount\":49.00,\"requestDate\":\"20180709\",\"requestNo\":\"20180709153527004977\",\"requestTime\":\"153527\",\"totaAmount\":49.00,\"userId\":\"13372007847\"}"},"resultCode":0,"resultMsg":"success"}
	//							String payNo = "200205333560821842";
								Map<String, String> maps = new HashMap<String, String>();
								maps.put("payNo", payNo);
								maps.put("payChannel", "ALIPAY");
								maps.put("bankCode", "undefined");
								maps.put("payMethod", "200");
								String payrefererurl = MaotaiString.PAY_REFERER_URL_NEW.replace("xxx", payNo);
								mwc = hcu.sendHttpPostProxy(MaotaiString.PAY_URL_NEW, mwc, maps, config, payrefererurl);
								System.out.println(zhanghao.get("code")+"---"+mwc.getContent());
								if(mwc.getContent().contains("会员信息不存在")) {
									zhanghao.put("buystatus", "1");
									maotaiService.updateZhanghaoBuyStatus(zhanghao);
									maotaiService.insertZhanghaoOrderItem(zhanghao);
									return;
								}
								
								//得到支付宝支付链接
								JSONObject payObj = JSONObject.parseObject(mwc.getContent()).getJSONObject("data");
								String html = payObj.getString("html");
								String buyurl = filterString(html);
								if(buyurl==null || "".equals(buyurl)||"null".equals(buyurl)){
									zhanghao.put("orderstatus", "0");
									maotaiService.updateZhanghaoOrderStatus(zhanghao);
									return;
								}
								zhanghao.put("buyurl", buyurl);
								zhanghao.put("buystatus", "1");
	//							maotaiService.insertZhanghaoOrderItem(zhanghao);
								maotaiService.updateZhanghaoBuyStatus(zhanghao);
								maotaiService.insertZhanghaoOrderItem(zhanghao);
							}else{
								zhanghao.put("buystatus", "1");
								maotaiService.updateZhanghaoBuyStatus(zhanghao);
								maotaiService.insertZhanghaoOrderItem(zhanghao);
							}
						}
					}
				}
			}
//			if(!isInsert){
//				zhanghao.put("orderstatus", "0");
//				maotaiService.updateZhanghaoOrder(zhanghao);
//			}
		}catch(Exception e ){
//			e.printStackTrace();
			System.out.println(zhanghao.get("code")+ "::query order exception---" + e.getMessage());
			try {
				zhanghao.put("orderstatus", "0");
				maotaiService.updateZhanghaoOrderStatus(zhanghao);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	public static String filterString(String html){
		String returnStr = "";
		Pattern p1 = Pattern.compile("window.location.href='(.*)';");  
		Matcher m = p1.matcher(html); 
		while(m.find()){  
			returnStr += m.group(1);
		}
		System.out.println(returnStr);  
		return returnStr;
	}
}
